<template>
  <view class="move-container">
    <view class="form-section">

      <view class="form-item">
        <text class="label">起始地码
          <text class="required">*</text>
        </text>
        <input
            v-model="formData.fromLocation"
            class="input"
            type="text"
            placeholder="请扫描或输入起始地码"
        />
      </view>

      <view class="form-item">
        <text class="label">区域
          <text class="required">*</text>
        </text>
        <picker
            mode="selector"
            :range="areaOptions"
            range-key="label"
            @change="handleAreaChange"
            :value="areaIndex"
        >
          <view class="input">
            {{ selectedAreaName || '请选择区域' }}
          </view>
        </picker>
      </view>

<!--      <view class="form-item">-->
<!--        <text class="label">目标地码-->
<!--          <text class="required">*</text>-->
<!--        </text>-->
<!--        <input-->
<!--            v-model="formData.toLocation"-->
<!--            class="input"-->
<!--            type="text"-->
<!--            placeholder="请扫描或输入目标地码"-->
<!--        />-->
<!--      </view>-->

      <!-- <view class="form-item">
         <text class="label">任务类型
           <text class="required">*</text>
         </text>
         <picker
           mode="selector"
           :range="taskType"
           range-key="label"
           @change="onBillChange"
           :value="billIndex">
           <view class="input">
             {{ taskType[billIndex] ? taskType[billIndex].label : '请选择任务类型' }}
           </view>
         </picker>
       </view>

       <view class="form-item">
         <text class="label">车辆
           <text class="required">*</text>
         </text>-->

      <!-- 	    <picker
              mode="selector"
              :range="chooseAGV"
              range-key="label"
              @change="chooseAGVcar"
              :value="agvId">
              <view class="input">
                {{ chooseAGV[agvId] ? chooseAGV[agvId].label : '请选择车辆' }}
              </view>
            </picker>
          </view> -->



      <view class="btn-group">
        <!--   <button @click="handleReset" class="btn btn-default">重置</button> -->
        <button @click="handleSubmit" class="btn btn-primary" :disabled="loading">
          <text v-if="loading" class="cuIcon-loading2 iconfont-spin"></text>
          {{ loading ? '提交中...' : '创建任务' }}
        </button>
      </view>
    </view>
  </view>
</template>

<script>

import {ManualTask,areaChoose} from '@/api/system/stock';
import {listSites, listAreas} from "../../api/system/site";

var main, receiver, filter;

export default {
  data() {
    return {
      taskType: [
        {value: '2', label: '入库'},
        {value: '1', label: '出库'},
      ],
      chooseAGV:[],
      billIndex: null,
      agvId: 0,
      materialList:[],
      selectedMaterialName: '',
      // 区域下拉框相关
      areaOptions: [
        { label: '验货区', value: '3' },
        { label: '立体库接驳位', value: '4' }
      ],
      areaIndex: null,
      selectedAreaName: '',
      formData: {
        // instrock: '',
        taskType: '',
        fromLocation: '',
        agvId: '',
        toLocation: '',
        barcode:'',
        area:''
        // remark: ''
      },
      loading: false
    };
  },

  onLoad() {
    this.initScan();
  },

  onShow() {
    this.startScan();
  },

  onHide() {
    this.stopScan();
  },

  onUnload() {
    this.stopScan();
  },

  methods: {
    handleMaterialPickerTap() {
      // 不再主动请求，数据由区域选择后自动加载
    },

    handleMaterialChange(e) {
      const index = e.detail.value;
      const selected = this.materialList[index];
      if (selected) {
        this.selectedMaterialName = selected.displayText || '未知物料';
        this.formData.fromLocation = selected.siteCode;
      }
    },

    handleAreaChange(e) {
      const index = e.detail.value;
      const selected = this.areaOptions[index];
      if (selected) {
        this.areaIndex = index;
        this.selectedAreaName = selected.label;
        this.formData.area = selected.value;
      }
    },

    // 新增：根据区域获取物料信息
    fetchMaterialListByArea(area) {
      listSites({ siteType: area.dictValue }).then(response => {
        // 拼接remark, goodsName, type为displayText
        this.materialList = (response.rows || []).map(item => ({
          ...item,
          displayText: [item.remark, item.goodsName, item.type].filter(Boolean).join(' / ')
        }));
        this.selectedMaterialName = '';
        this.formData.fromLocation = '';
      }).catch(error => {
        this.materialList = [];
        this.selectedMaterialName = '';
        this.formData.fromLocation = '';
        console.error('获取物料信息失败:', error);
      });
    },

    initScan() {
      let _this = this;
      /* #ifdef APP-PLUS */
      main = plus.android.runtimeMainActivity();
      var IntentFilter = plus.android.importClass('android.content.IntentFilter');
      filter = new IntentFilter();
      filter.addAction("com.service.scanner.data")
      receiver = plus.android.implements('io.dcloud.feature.internal.reflect.BroadcastReceiver', {
        onReceive: function (context, intent) {
          plus.android.importClass(intent);
          let code = intent.getStringExtra("ScanCode");
          console.log(code)
          _this.handleScanResult(code);
        }
      });
      /* #endif */
    },

    startScan() {
      /* #ifdef APP-PLUS */
      main.registerReceiver(receiver, filter);
      /* #endif */
    },

    stopScan() {
      /* #ifdef APP-PLUS */
      main.unregisterReceiver(receiver);
      /* #endif */
    },

    // 处理扫码结果
    handleScanResult(code) {
      // 判断扫码内容类型
      if (code.startsWith('L')) {
        // 库位格式
        this.formData.toLocation = code.substring(1);
      } else if (code.startsWith('M')) {
        // 物料编号格式（这里按照用户需求处理站点数据）
        if (this.materialList.length > 0) {
          const material = this.materialList.find(item => item.siteCode === code.substring(1));
          if (material) {
            this.formData.fromLocation = material.siteCode;
            this.selectedMaterialName = material.displayText;
          }
        }
      } else {
        // 默认当作终点站点处理
        this.formData.toLocation = code;
      }
    },

    // 重置表单
    handleReset() {
      this.formData = {
        fromLocation: '',
        toLocation: '',
        barcode:'',
        taskType: '',
        remark: ''
      };
      this.billIndex = null;
      this.selectedMaterialName = '';
    },

    // 提交表单
    handleSubmit() {
      if (this.loading) return;

      // 表单验证
      if (!this.formData.fromLocation) {
        this.$modal.msgError('请输入起始地码');
        return;
      }
      // if (!this.formData.toLocation) {
      //   this.$modal.msgError('请输入目的标地码');
      //   return;
      // }
      if (!this.formData.area) {
        this.$modal.msgError('请选择区域');
        return;
      }

      this.loading = true;
      areaChoose(this.formData).then(() => {
        this.handleReset();
        this.$modal.msgSuccess("任务成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    }
  }
}
</script>

<style lang="scss" scoped>
/* 样式保持不变 */
.move-container {
  min-height: 100vh;
  background-color: #f8f9fa;
  padding: 16px;
}
.move-container {
  min-height: 100vh;
  background-color: #f8f9fa;
  padding: 16px;
}

.form-section {
  background-color: #fff;
  border-radius: 8px;
  padding: 16px;

  .form-item {
    margin-bottom: 16px;

    .label {
      display: block;
      font-size: 14px;
      color: #333;
      margin-bottom: 8px;
      font-weight: 500;

      .required {
        color: #ff4d4f;
        margin-left: 4px;
      }
    }

    .input {
      width: 100%;
      height: 40px;
      background-color: #f8f9fa;
      border-radius: 4px;
      padding: 0 12px;
      font-size: 14px;
      color: #333;
      display: flex;
      align-items: center;
    }
  }
}

.btn-group {
  display: flex;
  justify-content: space-between;
  margin-top: 24px;

  .btn {
    width: 48%;
    height: 40px;
    border-radius: 4px;
    font-size: 14px;
    font-weight: 500;

    &.btn-default {
      background-color: #f8f9fa;
      color: #666;
    }

    &.btn-primary {
      background-color: #4A90E2;
      color: #fff;

      &:disabled {
        opacity: 0.7;
      }
    }
  }
}

.iconfont-spin {
  display: inline-block;
  animation: loading-rotate 2s linear infinite;
}

@keyframes loading-rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>